package com.servlets.user.group;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.core.GlobalConstants;
import com.core.ListUtils;
import com.core.protocols.IKVObject;
import com.core.protocols.IServiceLayerDelegate;
import com.model.mapparser.UserGroupMapParser;
import com.model.user.UserGroup;
import com.servicelayer.user.UserGroupListLayer;
import com.servlets.TaskTrackerServlet;

/**
 * Servlet implementation class GroupCreate
 */
public class UserGroupAdd
        extends TaskTrackerServlet
        implements IServiceLayerDelegate {

    private static final long   serialVersionUID = 1L;
    private HttpServletResponse postResponse     = null;



    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserGroupAdd() {

        super();

    }



    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    @SuppressWarnings("unchecked")
    protected void doPost ( HttpServletRequest request,
                            HttpServletResponse response )
            throws ServletException, IOException {


        this.postResponse = response;

        UserGroup template = null;
        Map <String, String[]> map = null;
        map = request.getParameterMap();
        template = UserGroupMapParser.fromMap(map);

        UserGroupListLayer groupListLayer = new UserGroupListLayer();
        groupListLayer.setLayerDelegate(this);


        try {
            UserGroupListLayer.createEntityWithTemplate(template, groupListLayer.getLayerDelegate(), null);
        } catch ( Exception e ) {

        }


    }



    @Override
    public <T> void responseResponseItemsList ( final List <T> items,
                                                final Object request,
                                                final Exception exception ) {

        T item = ListUtils.listItemAtIndex(items, 0);

        this.redirectItemIntoOpenServlet(item);

    }



    private <T> void redirectItemIntoOpenServlet ( T item ) {

        if ( this.postResponse == null ) {
            return;
        }

        String redirection = String.format("%s", GlobalConstants.SERVLET_ADMINISTRATION);

        if ( item != null ) {
            if ( item instanceof IKVObject ) {
                IKVObject kvObject = (IKVObject) item;
                String idValue = kvObject.idValue().toString();
                redirection = String.format("%s?%s", GlobalConstants.SERVLET_GROUPINFO, idValue);
            }
        }

        try {
            this.postResponse.sendRedirect(redirection);
        } catch ( IOException e ) {
            e.printStackTrace();
        }

    }


}
